package ru.ifmo.swing.genetics.config.common;

import ru.ifmo.swing.Panel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

/**
 * @author avhaliullin
 */
public class FileChooser extends Panel {
    private String fileName;

    public String getFileName() {
        return fileName;
    }

    public FileChooser(final ChooserListener<File> listener) {
        setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
        final JTextField fileName = new JTextField();
        final JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File("."));
        fileName.setEditable(false);
        JButton browse = new JButton("Browse");
        browse.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                switch (chooser.showOpenDialog(FileChooser.this)) {
                    case JFileChooser.APPROVE_OPTION: {
                        FileChooser.this.fileName = chooser.getSelectedFile().getAbsolutePath();
                        fileName.setText(getFileName());
                        listener.chosen(chooser.getSelectedFile());
                    }
                    break;
                    case JFileChooser.CANCEL_OPTION: {
                        //ignore
                    }
                    break;
                    case JFileChooser.ERROR_OPTION: {
                        //ignore
                    }
                }
            }
        });
        fileName.setPreferredSize(new Dimension(300, 25));
        fileName.setMaximumSize(new Dimension(2000, 25));
        add(fileName);
        add(browse);
    }

}
